{% extends 'base.html' %}
{% block title %}
{{ main.title }} 详情 - 数据管理系统
{% endblock %} {% block breadcrumb %}
<li class="breadcrumb-item">
  <a href="{{ url_for('list_main') }}">产品列表</a>
</li>
<li class="breadcrumb-item active" aria-current="page">{{ main.title }}</li>
{% endblock %} {% block content %}
<div class="card mb-4">
  <div class="card-body">
    <!-- 标题部分 -->
    <div class="d-flex justify-content-between align-items-start mb-3">
      <div>
        <h2 class="mb-2"><a href="{{ main.url }}" target="_blank" class="text-decoration-none">{{ main.title }}</a></h2>
        <div class="text-muted">
          <span class="fw-bold">公司名称:</span>
          <a href="{{ main.company_url }}" target="_blank" class="text-decoration-none">
            {{ main.company_name }}
            <i class="bi bi-box-arrow-up-right ms-1"></i>
          </a>
        </div>

        {% if details.0.price_ranges %}
        <div class="mt-2">
          <strong>阶梯价格:</strong>
          <table class="table table-sm table-bordered mt-1 mb-0">
            <thead class="table-light">
              <tr>
                <th>数量区间</th>
                <th>价格</th>
              </tr>
            </thead>
            <tbody>
              {% for p in details.0.price_ranges %}
              <tr>
                <td>{{ p.range }}</td>
                <td>{{ p.price }}</td>
              </tr>
              {% endfor %}
            </tbody>
          </table>
        </div>
        {% else %}
        <p class="text-muted">暂无阶梯价格</p>
        {% endif %}
      </div>
    </div>

    <!-- 操作按钮部分 -->
    <div class="d-flex justify-content-between align-items-center mb-3 pt-2 border-top">
      <h5 class="mb-0 text-muted">产品型号列表</h5>
      <div class="d-flex">
        <button id="batchEditBtn" class="btn btn-primary me-2" onclick="saveBatchEdits()"><i class="bi bi-check-lg"></i>
          保存所有更改（Alt + B）</button>
        <a href="{{ url_for('add_details', product_id=main.id) }}" class="btn btn-primary me-2"><i
            class="bi bi-plus-lg"></i> 添加详情</a>
        <a href="{{ url_for('list_main') }}" class="btn btn-outline-secondary"><i class="bi bi-arrow-left"></i> 返回</a>
      </div>
    </div>

    <!-- 图片大小调整滑块 -->
    <div class="mb-3">
      <label for="imageSizeSlider" class="form-label">图片大小调整</label>
      <div class="d-flex align-items-center">
        <input type="range" class="form-range" id="imageSizeSlider" min="50" max="800" value="150" step="10" />
        <span id="imageSizeValue" class="ms-2">150px</span>
      </div>
    </div>
  </div>
</div>
<button class="btn btn-outline-secondary me-2" onclick="toggleBatchFill()">
  <i class="bi bi-pencil-square"></i> 批量填充字段(Alt + F)
</button>
<!-- 批量填充区域 -->
<div id="batch-fill-container" class="card mt-3" style="display: none;">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-bordered mb-0">
        <thead class="table-light">
          <tr>
            <th style="width: 5%">序号</th>
            <th style="width: 20%">图片</th>
            <th style="width: 20%">对方型号</th>
            <th style="width: 20%">自用型号</th>
            <th style="width: 20%">描述</th>
            <th style="width: 20%">描述（英文）</th>
            <th style="width: 10%">价格</th>
            <th style="width: 5%">库存</th>
            <th style="width: 20%">操作</th>
          </tr>
        </thead>
        <tbody id="batch-fill-body">
          <tr>
            <td>#</td>
            <td>--</td>
            <td>--</td>
            <td>--</td> <!-- 自用型号列，留空不填充 -->
            <td><textarea class="form-control form-control-sm" rows="2" placeholder="批量填充值"></textarea></td>
            <td><textarea class="form-control form-control-sm" rows="2" placeholder="批量填充值（英文）"></textarea></td>
            <td>--</td>
            <td>--</td>
            <td>
              <button class="btn btn-sm btn-primary" onclick="applyBatchFill()">
                <i class="bi bi-arrow-down-square"></i> 应用填充
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- 产品列表表格 -->
<div class="card">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped table-hover mb-0" id="details-table">
        <thead class="table-light">
          <tr>
            <th scope="col" style="width: 5%">序号</th>
            <th scope="col" style="width: 20%">图片</th>
            <th scope="col" style="width: 20%">对方型号</th>
            <th scope="col" style="width: 20%">自用型号</th>
            <th scope="col" style="width: 20%">描述</th>
            <th scope="col" style="width: 20%">描述（英文）</th>
            <th scope="col" style="width: 10%">价格</th>
            <th scope="col" style="width: 5%">库存</th>
            <th scope="col" style="width: 20%">操作</th>
          </tr>
        </thead>
        <tbody>
          {% for detail in details %}
          <tr data-id="{{ detail.id }}">
            <th scope="row" class="serial-number"></th>
            <td>
              {% if detail.image_url == '原链接无图' %}
              <span class="text-muted">原链接无图</span>
              {% else %}
              <a href="javascript:void(0);" onclick="showImageModal('{{ detail.display_image_url }}')"
                title="{{ detail.description }}"><img src="{{ detail.display_image_url }}"
                  class="img-thumbnail product-image" style="max-width: 150px" alt="{{ detail.description }}" /></a>
              {% endif %}
            </td>
            <td>{{ detail.other_model }}</td>
            <td>
              <div class="edit-field">
                <input type="text" class="form-control form-control-sm" style="min-height: 100px;"
                  value="{{ detail.self_model }}" />
              </div>
            </td>
            <td>
              <div class="edit-field">
                <textarea class="form-control form-control-sm" rows="2"
                  style="min-height: 100px;">{{ detail.description }}</textarea>
              </div>
            </td>
            <td>
              <div class="edit-field">
                <textarea class="form-control form-control-sm" rows="2"
                  style="min-height: 100px;">{{ detail.description_en }}</textarea>
              </div>
            </td>
            <td>¥{{ '%.2f'|format(detail.price) }}</td>
            <td>{{ detail.stock_str }}</td>

            <td class="action-buttons">
              <a href="{{ url_for('edit_details', id=detail.id) }}" class="btn btn-sm btn-outline-primary me-1"><i
                  class="bi bi-pencil"></i> 编辑</a>
              <a href="{{ url_for('delete_details', id=detail.id) }}" class="btn btn-sm btn-outline-danger"
                onclick="return confirm('确定删除吗?')"><i class="bi bi-trash"></i> 删除</a>
            </td>
          </tr>
          {% endfor %}
        </tbody>
      </table>
    </div>
  </div>
</div>
<!-- 图片模态框 -->
<div class="modal fade" id="imageModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-xl">
    <div class="modal-content bg-transparent border-0">
      <div class="modal-body p-0 text-center">
        <img id="modalImage" src="" alt="放大图片" class="img-fluid modal-image" style="max-height: 80vh" />
      </div>
    </div>
  </div>
</div>
{% endblock %} {% block scripts %}
<script>
  document.addEventListener('DOMContentLoaded', function () {
    // 为表格中的每一行添加序号
    const rows = document.querySelectorAll('#details-table tbody tr')
    rows.forEach((row, index) => {
      const serialCell = row.querySelector('.serial-number')
      if (serialCell) {
        serialCell.textContent = index + 1
      }
    })

    // 初始化图片大小滑块
    const slider = document.getElementById('imageSizeSlider')
    const sizeValue = document.getElementById('imageSizeValue')
    const productImages = document.querySelectorAll('.product-image')

    // 更新图片大小的函数
    function updateImageSize(width) {
      productImages.forEach((img) => {
        img.style.width = `${width}px`
        img.style.maxWidth = 'none'
      })
      sizeValue.textContent = `${width}px`
    }

    // 监听滑块变化
    slider.addEventListener('input', function () {
      updateImageSize(this.value)
    })

    // 初始化图片大小
    updateImageSize(slider.value)

    // 为编辑字段添加样式
    document.querySelectorAll('.edit-field input, .edit-field textarea').forEach(el => {
      el.style.border = '1px solid #ddd';
      el.style.backgroundColor = '#f8f9fa';

      // 添加聚焦效果
      el.addEventListener('focus', function () {
        this.style.backgroundColor = '#fff';
        this.style.borderColor = '#86b7fe';
        this.style.boxShadow = '0 0 0 0.25rem rgba(13,110,253,.25)';
      });

      // 添加失焦效果
      el.addEventListener('blur', function () {
        this.style.backgroundColor = '#f8f9fa';
        this.style.borderColor = '#ddd';
        this.style.boxShadow = 'none';
      });
    });
  })

  // 显示图片模态框
  function showImageModal(imageUrl) {
    const modalImage = document.getElementById('modalImage')
    modalImage.src = imageUrl

    modalImage.style.width = 'auto'
    modalImage.style.maxWidth = '100%'
    modalImage.style.maxHeight = '80vh'

    var modal = new bootstrap.Modal(document.getElementById('imageModal'))
    modal.show()
  }

  // 点击模态框背景关闭
  document.getElementById('imageModal').addEventListener('click', function (e) {
    if (e.target === this) {
      bootstrap.Modal.getInstance(this).hide()
    }
  })

  // 点击图片不关闭模态框
  document.getElementById('modalImage').addEventListener('click', function (e) {
    e.stopPropagation()
  })

  // 批量保存编辑的函数
  async function saveBatchEdits() {
    // 收集所有修改的数据（只处理可编辑字段）
    const editData = [];
    const rows = document.querySelectorAll('#details-table tbody tr[data-id]');

    rows.forEach(row => {
      const id = row.getAttribute('data-id');
      const data = { id: id };

      // 只收集实际可编辑的字段（自用型号、描述、描述英文）
      const selfModelInput = row.querySelector('td:nth-child(4) input');
      const descriptionTextarea = row.querySelector('td:nth-child(5) textarea');
      const descriptionEnTextarea = row.querySelector('td:nth-child(6) textarea');

      // 只添加存在的字段
      if (selfModelInput) data.self_model = selfModelInput.value;
      if (descriptionTextarea) data.description = descriptionTextarea.value;
      if (descriptionEnTextarea) data.description_en = descriptionEnTextarea.value;

      editData.push(data);
    });

    // 过滤掉没有实际修改的行（至少包含一个可编辑字段）
    const validData = editData.filter(item => Object.keys(item).length > 1);

    if (validData.length === 0) {
      showFlash('没有可提交的编辑数据', 'info');
      return;
    }

    try {
      // 显示加载状态
      const batchEditBtn = document.getElementById('batchEditBtn');
      const originalText = batchEditBtn.innerHTML;
      batchEditBtn.disabled = true;
      batchEditBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> 提交中...';

      // 发送AJAX请求（不包含CSRF头）
      const response = await fetch('/details/batch_edit', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'  // 仅保留内容类型头
        },
        body: JSON.stringify(validData)
      });

      if (!response.ok) {
        throw new Error(`请求失败，状态码: ${response.status}`);
      }

      const result = await response.json();

      // 处理响应
      if (result.success) {
        showFlash('批量更新成功', 'success');
        // 1.5秒后刷新页面
        setTimeout(() => {
          window.location.reload();
        }, 1500);
      } else {
        showFlash(result.message || '更新失败', 'error');
      }
    } catch (error) {
      console.error('提交错误:', error);
      showFlash('提交失败，请重试', 'error');
    } finally {
      // 恢复按钮状态
      const batchEditBtn = document.getElementById('batchEditBtn');
      batchEditBtn.disabled = false;
      batchEditBtn.innerHTML = originalText;
    }
  }

  // 显示消息提示
  function showFlash(message, category) {
    const flashDiv = document.createElement('div');
    flashDiv.className = `fixed top-4 right-4 px-4 py-3 rounded shadow-lg z-50 transition-all duration-500 transform translate-x-full opacity-0 ${category === 'success' ? 'bg-green-500 text-white' :
      category === 'error' ? 'bg-red-500 text-white' :
        'bg-blue-500 text-white'
      }`;
    flashDiv.innerHTML = `
        <div class="flex items-center">
            <i class="bi ${category === 'success' ? 'bi-check-circle' : 'bi-exclamation-circle'} mr-2"></i>
            <span>${message}</span>
        </div>
    `;

    document.body.appendChild(flashDiv);

    // 显示动画
    setTimeout(() => {
      flashDiv.classList.remove('translate-x-full', 'opacity-0');
    }, 10);

    // 3秒后隐藏
    setTimeout(() => {
      flashDiv.classList.add('translate-x-full', 'opacity-0');
      setTimeout(() => {
        document.body.removeChild(flashDiv);
      }, 500);
    }, 3000);
  }
  function toggleBatchFill() {
    const container = document.getElementById('batch-fill-container');
    if (container.style.display === 'none') {
      container.style.display = 'block';
    } else {
      container.style.display = 'none';
    }
  }

  // 将批量填充值应用到主表格
  function applyBatchFill() {
    const batchRow = document.querySelector('#batch-fill-body tr');
    const fillDesc = batchRow.querySelector('td:nth-child(5) textarea').value;
    const fillDescEn = batchRow.querySelector('td:nth-child(6) textarea').value;

    const rows = document.querySelectorAll('#details-table tbody tr');

    rows.forEach(row => {
      const descTextarea = row.querySelector('td:nth-child(5) textarea');
      const descEnTextarea = row.querySelector('td:nth-child(6) textarea');

      if (fillDesc) descTextarea.value = fillDesc;
      if (fillDescEn) descEnTextarea.value = fillDescEn;
    });

    showFlash('描述字段已批量填充（不包括自用型号）', 'success');
  }

  document.addEventListener('keydown', function (e) {
    // Alt + B 快捷键（区分大小写）
    if (e.altKey && e.key.toLowerCase() === 'b') {
      e.preventDefault(); // 阻止默认行为，如“书签”
      saveBatchEdits();
    }
    // Alt + F 快捷键（区分大小写）
    if (e.altKey && e.key.toLowerCase() === 'f') {
      e.preventDefault(); // 阻止默认行为，如“书签”
      toggleBatchFill();
    }
  });

</script>

{% endblock %}


